<template>
  <div v-loading="loading">
    <el-tabs v-model="currentTab" type="border-card" class="j-tabs" @tab-change="onTabChange">
      <el-tab-pane name="1" label="静态住宅">
        <div class="proxy-form mt-0">
          <div class="form-main">
            <div class="form">
              <el-form label-width="120px" :model="proxyForm" ref="proxyFormRef" :rules="rules" size="large">
                <el-form-item label="国家/地区" prop="country_code">
                  <el-select
                    v-model="proxyForm.country_code"
                    filterable
                    clearable
                    placeholder="请选择国家和地区"
                    class="full-width"
                    @change="onCountryChange"
                  >
                    <el-option v-for="item in countryList" :key="item.code" :label="item.name" :value="item.code" />
                  </el-select>
                </el-form-item>
                <el-form-item label="IP类型" prop="line_type">
                  <el-radio-group v-model="proxyForm.line_type" @change="onLineTypeChange">
                    <el-radio value="2" size="large" border>标准</el-radio>
                    <el-radio value="3" size="large" border>高级</el-radio>
                  </el-radio-group>
                  <div class="form-item-tips">
                    <el-icon size="18px" color="#999"><QuestionFilled /></el-icon>
                    <span v-if="proxyForm.line_type == '2'">高纯净度IP，满足大部分业务场景需求</span>
                    <span v-else-if="proxyForm.line_type == '3'">更纯净的代理地址，高度隐蔽的同时享有高性价比</span>
                  </div>
                </el-form-item>
                <el-form-item label="业务用途" prop="business">
                  <el-select
                    v-model="proxyForm.business"
                    filterable
                    clearable
                    placeholder="请选择业务用途"
                    class="full-width"
                    @change="onBusinessChange"
                  >
                    <el-option v-for="item in businessList" :key="item" :label="item" :value="item" />
                  </el-select>
                </el-form-item>
                <el-form-item label="选择套餐" prop="days">
                  <el-radio-group v-model="proxyForm.days">
                    <el-radio value="30" size="large" border>30天</el-radio>
                    <el-radio value="60" size="large" border>60天</el-radio>
                    <el-radio value="90" size="large" border>90天</el-radio>
                    <el-radio value="360" size="large" border>360天</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="购买数量" prop="quantity">
                  <el-input v-model.number="proxyForm.quantity" type="number" :min="1" autocomplete="off" placeholder="请输入购买数量" />
                </el-form-item>
                <el-form-item label="支付方式" prop="pay_way">
                  <el-radio-group v-model="proxyForm.pay_way" class="pay-way-list">
                    <el-radio label="alipay" border>
                      <span class="form-pay-icon">
                        <img src="@/assets/ipx-proxy_160.png" class="img" />
                        <span>支付宝</span>
                      </span>
                    </el-radio>
                    <el-radio label="card" border>
                      <span class="form-pay-icon">
                        <img src="@/assets/ipx-proxy_150.png" class="img" />
                        <span>信用卡</span>
                      </span>
                    </el-radio>
                    <el-radio label="usdt" border>
                      <span class="form-pay-icon">
                        <img src="@/assets/ipx-proxy_156.png" class="img" />
                        <span>USDT</span>
                      </span>
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="应付金额">
                  <div class="form-amount">
                    <span>$</span>
                    <strong>{{ amount }}</strong>
                  </div>
                </el-form-item>
                <el-form-item label="" label-width="24px">
                  <div class="form-submit-tips">
                    <span>· 提供的代理<strong>仅限在中国大陆以外的地区使用</strong>，且受当地网络监管，请合法合规使用；</span>
                    <span>· 代理售出后，<strong>不支持退换</strong>，购买前请确认代理类型及地区避免误购；</span>
                  </div>
                </el-form-item>
                <el-form-item>
                  <div style="white-space: nowrap">
                    <el-button
                      class="primary-btn"
                      style="width: 134px"
                      type="primary"
                      :disabled="loading"
                      :loading="loading"
                      @click="onSubmit(proxyFormRef)"
                      >确认购买</el-button
                    >
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <div class="form-tips">
            <p class="title">Q: 什么是静态住宅代理?</p>
            <p class="info">A: 静态住宅代理提供来自真实住宅网络的固定IP地址，确保长期稳定性和高匿名性。</p>

            <p class="title">Q: 什么时候应该使用静态住宅代理?</p>
            <p class="info">A: 当需要一致IP地址的业务时，例如管理多个社交媒体账户、访问特定地区的服务和维持连续的在线会话。</p>

            <p class="title">Q: 如何设置静态住宅代理？</p>
            <p class="info">A: 购买代理计划并使用提供的代理 IP、端口、用户名和密码配置您的应用程序。</p>

            <p class="title">Q: 如何获得静态住宅代理的免费试用？</p>
            <p class="info">A: 静态产品目前不提供免费测试。动态住宅线路，在用户注册激活后，可以领取免费流量包进行测试。</p>

            <p class="title">Q: 静态住宅代理适合网页抓取吗?</p>
            <p class="info">A: 静态住宅代理非常适合需要稳定IP的网页抓取任务，以避免触发反抓取机制，确保不间断的数据收集。</p>

            <p class="title">Q: 我可以用你们线路翻墙吗？</p>
            <p class="info">A: 不可以！线路已经屏蔽所有境内的IP访问，使用线路前，您需要自备境外环境。</p>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane name="2" label="已购线路">
        <Record ref="recordRef" :countryList="countryList" :businessList="businessList" @page-loading="onPgeLoading" />
      </el-tab-pane>
    </el-tabs>

    <Pay ref="payRef" payType="static" />
  </div>
</template>

<script lang="ts" setup>
  import { ref, watch, nextTick } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { useUserStore } from '@/store/modules/user';
  import { setLang } from '@/i18n';
  import { useI18n } from 'vue-i18n';
  import { staticRegionApi, businessApi } from '@/api/index';
  import type { FormInstance, FormRules } from 'element-plus';
  import { QuestionFilled } from '@element-plus/icons-vue';
  import Record from './components/record.vue';
  import { calculatePrice } from '@/utils/index';
  import Pay from '../pay/zh-cn.vue';

  const { locale } = useI18n();

  const route = useRoute();
  const router = useRouter();
  const userStore = useUserStore();

  const getUserInfo = computed(() => {
    let userInfo = userStore.getUserInfo || {};
    return userInfo;
  });

  const amount = computed(() => {
    return calculatePrice(proxyForm.line_type, proxyForm.days, proxyForm.quantity);
  });

  const props = defineProps<{
    data: Array;
  }>();

  const emits = defineEmits<{
    (event: 'confirm'): void;
    (event: 'page-change'): void;
  }>();

  const recordRef = ref();
  const payRef = ref();
  const loading = ref(false);
  const currentTab = ref('1');
  const proxyFormRef = ref<FormInstance>();
  const proxyForm = reactive({
    country_code: '',
    country_code_str: '',
    line_type: '2',
    line_type_str: '标准',
    business: '',
    business_str: '',
    days: '30',
    quantity: 1,
    pay_way: 'alipay',
  });
  const rules = reactive<FormRules>({
    country_code: [{ required: true, message: '请选择国家和地区', trigger: 'change' }],
    line_type: [{ required: true, message: '请选择IP类型', trigger: 'change' }],
    business: [{ required: true, message: '请选择业务用途', trigger: 'change' }],
    days: [{ required: true, message: '请选择套餐', trigger: 'change' }],
    quantity: [{ required: true, message: '请输入购买数量', trigger: 'change' }],
    pay_way: [{ required: true, message: '请选择支付方式', trigger: 'change' }],
  });

  const countryList = ref([]);
  const businessList = ref([]);

  const onSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
      if (valid) {
        onBuy(proxyForm);
      }
    });
  };

  const onReset = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
  };

  const onTabChange = (val) => {
    if (val == '2') {
      recordRef.value.onPageChange('staticProxy', 1);
    }
  };

  const onCountryChange = (val) => {
    let obj = countryList.value.find((v) => (v.code == val));
    proxyForm.country_code_str = obj.name || '';
  };

  const onLineTypeChange = (val) => {
    if (val == 2) {
      proxyForm.line_type_str = '标准';
    } else if (val == 3) {
      proxyForm.line_type_str = '高级';
    }
  };

  const onBusinessChange = (val) => {
    let str = businessList.value.find((v) => (v == val));
    proxyForm.business_str = str || '';
  };

  const getRegion = async (type) => {
    staticRegionApi({})
      .then((res) => {
        if (res.data) {
          if (type == 'country') {
            countryList.value = res.data;
          }
        }
      })
      .catch((err) => {
        console.log('err', err);
        ElMessage.error(err.message);
      });
  };

  const getBusiness = async () => {
    businessApi({})
      .then((res) => {
        if (res.data) {
          businessList.value = res.data;
        }
      })
      .catch((err) => {
        console.log('err', err);
        ElMessage.error(err.message);
      });
  };

  const onPgeLoading = (val) => {
    loading.value = val;
  };

  const onBuy = (item) => {
    emits('log', item);
    payRef.value.onBuy({
      ...item,
      amount,
      payType: 'static',
    });
  };

  onMounted(() => {
    currentTab.value = route.query.name || '1';
    getRegion('country');
    getBusiness();
  });

  watch(
    () => locale.value,
    () => {
      currentTab.value = route.query.name || '1';
      getRegion('country');
      getBusiness();
    },
    { deep: true, immediate: true },
  );
</script>

<style scoped lang="scss">
  .proxy-form {
    min-width: 1100px;
    justify-content: center;
  }

  .form-submit-tips {
    min-height: 18px;
    padding: 0;
    margin: 0 0 0 96px;
    font-size: 14px;
    color: #666;
    line-height: 24px;

    span {
      display: block;
    }

    strong {
      color: #fa1801;
    }
  }

  .form-item-tips {
    display: inline-flex;
    flex-direction: row;
    justify-content: flex-start;
    align-content: center;
    align-items: center;
    min-height: 18px;
    padding: 0;
    margin: 0 0 0 20px;
    border-radius: 0;
    background: #fff;
    font-size: 14px;
    color: #999;
    line-height: 18px;

    span {
      padding-left: 5px;
    }
  }

  .form-amount {
    display: inline-flex;
    flex-direction: row;
    justify-content: flex-start;
    align-content: center;
    align-items: center;
    height: 28px;
    font-size: 20px;
    color: #ff7928;
    font-weight: bold;
    line-height: 28px;

    strong {
      font-size: 28px;
      margin-top: -2px;
      margin-left: 4px;
    }
  }

  .form-pay-icon {
    display: inline-flex;
    flex-direction: row;
    justify-content: flex-start;
    align-content: center;
    align-items: center;
    height: 21px;
    vertical-align: middle;
  }
</style>
